import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author wangj881
 * @date 2025-03-11 17:41
 */
public class L46_3 {

    class Solution {
        public List<List<Integer>> permute(int[] nums) {
            ArrayList<List<Integer>> lists = new ArrayList<>();
            LinkedList<Integer> list = new LinkedList<Integer>();
            boolean[] used = new boolean[nums.length];

            permute(nums, list, lists, used);

            return lists;
        }

        private void permute(int[] nums, LinkedList<Integer> list, ArrayList<List<Integer>> lists, boolean[] used) {
            if (list.size() == nums.length) {
                lists.add(new ArrayList<>(list));
                return;
            }
            for (int i = 0; i < nums.length; i++) {
                if (used[i]) {
                    continue;
                }

                list.addLast(nums[i]);
                used[i] = true;

                permute(nums, list, lists, used);

                list.removeLast();
                used[i] = false;
            }
        }
    }
}
